package test;

import java.io.ByteArrayOutputStream;

public class BcdCodeUtil {

	public static byte[] str2cbcd(String s) {
		if (s.length() % 2 != 0) {
			s =  s + (char)0x3F; // (3F - 48) = 15(F)
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		char[] cs = s.toCharArray();
		for (int i = 0; i < cs.length; i += 2) {
			int high = cs[i] - 48;
			int low = cs[i + 1] - 48;
			baos.write(high << 4 | low);
		}
		return baos.toByteArray();
	}
	
	public static byte[] str2cbcd(byte[] src) {
		byte [] newbytes = null;
		if (src.length % 2 != 0) {
			newbytes = new byte[src.length + 1];
			System.arraycopy(src, 0, newbytes, 0, src.length);
			newbytes[src.length] = (byte)0x3F;
		} else {
			newbytes = src;
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		for (int i = 0; i < newbytes.length; i += 2) {
			int high = newbytes[i] - 48;
			int low = newbytes[i + 1] - 48;
			baos.write(high << 4 | low);
		}
		return baos.toByteArray();
	}

	public static String cbcd2string(byte[] b) {
		StringBuffer sb = new StringBuffer();
		int actualnum = b.length;
		if ( (b[b.length - 1] & 0x0F) == 15) {
			actualnum -= 1;
		}
		for (int i = 0; i < actualnum; i++) {
			int h = ((b[i] & 0xff) >> 4) + 48;
			sb.append((char) h);
			int l = (b[i] & 0x0f) + 48;
			sb.append((char) l);
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		byte[] bcd = str2cbcd("000331088880007");
		System.out.println( bcd.length );
		System.out.println( BitConvert.Hex2Str(bcd) );
		
		for (int i = 0; i < bcd.length; i++) {
			if ( Integer.toHexString(0xFF & bcd[i]).length() == 1 ) {
				System.out.println( "0" + Integer.toHexString(0xFF & bcd[i]) );
			} else {
				System.out.println( Integer.toHexString(0xFF & bcd[i]) );
			}
		}
		System.out.println(cbcd2string(bcd));
	}
}
